<template>
  <van-nav-bar title="添加地址" left-text="" @click-left="onClickLeft" left-arrow>
    <template #right>
      <van-icon name="location-o" size="18" v-model="flag"  @click="isflag"/>
    </template>
  </van-nav-bar>
  <van-address-edit :area-list="areaList" show-set-default show-search-result :search-result="searchResult"
    :area-columns-placeholder="['请选择', '请选择', '请选择']" @save="onSave" @change-detail="onChangeDetail"
    :address-info="addressData"
    />
  <AMapLocation v-if="flag==true"/>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { showToast } from 'vant';
import { areaList } from '@vant/area-data';
import { POST } from '../services/request';
import { useRouter } from 'vue-router';
import AMapLocation from '@/components/AMapLocation.vue'
const router = useRouter();

// 默认填入的数据
const addressData = ref({})

// 获取定位的信息
const locationAddress = JSON.parse(localStorage.getItem('addressData'));

// 是否点击
const flag = ref(false);


const searchResult = ref([]);
// 获取用户信息  转为json对象
const userData = JSON.parse(localStorage.getItem('LoginUser'));

// 用户id
const uid = ref(null);
uid.value = userData.id;

onMounted(async () => {
  // console.log(locationAddress);
})
// 定位按钮点击
const isflag = async()=>{
  flag.value =! flag.value
  // console.log(flag.value);
  if(flag.value==true){
    addressData.value.areaCode = locationAddress.adcode
  }
}
// 保存
const onSave = async (info) => {
  // console.log(info.name);
  const saveAddressRes = await POST({
    url: '/Address/addAddress',
    params: {
      uid: uid.value,
      addressDetail: info.addressDetail,
      areaCode: info.areaCode,
      tel: info.tel,
      isDefault: info.isDefault,
      name: info.name,
    }
  })
  if (saveAddressRes.code === 1) {
    showToast(saveAddressRes.msg);
    router.push('address');
  }
};

const onChangeDetail = (val) => {
  if (val) {
    searchResult.value = [
      {
        name: '黄龙万科中心',
        address: '杭州市西湖区',
      },
    ];
  } else {
    searchResult.value = [];
  }
};

// 返回
const onClickLeft = () => history.back();
</script>